<script setup lang="ts">

import {ref, defineExpose, onUnmounted, onMounted} from "vue";

const dialogVisible = ref(false)
const videoUrl = ref("")
const videoElement = ref<HTMLVideoElement | null>(null)
const isPlaying = ref(false)

const handleDialogClosed = ()=>{
  videoElement.value?.pause()
}

// 播放/暂停切换
const togglePlay = () => {
  if (!videoElement.value) return

  if (isPlaying.value) {
    videoElement.value.pause()
  } else {
    videoElement.value.play()
  }
  isPlaying.value = !isPlaying.value
}


// 全屏
const toggleFullscreen = () => {
  if (!videoElement.value) return

  if (document.fullscreenElement) {
    document.exitFullscreen()
  } else {
    videoElement.value.requestFullscreen()
  }
}

// 键盘快捷键
const handleKeyDown = (e: KeyboardEvent) => {
  if (!videoElement.value) return

  switch (e.key) {
    case ' ':
      togglePlay()
      break
    case 'f':
      toggleFullscreen()
      break
    case 'ArrowLeft':
      videoElement.value.currentTime -= 5
      break
    case 'ArrowRight':
      videoElement.value.currentTime += 5
      break
  }
}

// 添加事件监听
onMounted(() => {
  window.addEventListener('keydown', handleKeyDown)
})

// 移除事件监听
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
})
defineExpose({
  dialogVisible,
  videoUrl
})

</script>

<template>
  <el-dialog v-model="dialogVisible" @closed="handleDialogClosed">
    <div>
      <video
        ref="videoElement"
        controls
      >
        <source :src="videoUrl" type="video/mp4">
        您的浏览器不支持 HTML5 视频
      </video>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
